﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;

public class StudyPhonicsManager : Singleton<StudyPhonicsManager>
{

    public const string ADS_TIPS = "观看广告可以解锁D字母的学习";

    private StudyPhonicsUI uiView;
    private StudyPhonicesModel model;

    private bool isGaming = false;

    private int curLetter;

    private PhonicsGameBase curGame;

    private Vector3[] paths = new Vector3[10];

    public int StartIndex;
    //是否设置 翻转ledi
    public bool isTurnLeDi = true;
    private bool isHideLd = false;
    private bool isShowEncourage = true;
    private bool isLockInput = false;

    //乐迪翻转的偏移值
    private float offsetX = 80;
    private float offsetY = 20;

    private const string phonicsrecord = "phonicsrecord";

    public override void Init()
    {
        base.Init();

        StartIndex = (int)'A';

        this.model = new StudyPhonicesModel();
        paths[0] = new Vector3(-705f, -323f, -462);//(-620f, -303f, -462); - 80  - 20
        paths[1] = new Vector3(-383f, -270f, -462);
        paths[2] = new Vector3(-23f, -225f, -462);
        paths[3] = new Vector3(283f, -253f, -462);
        paths[4] = new Vector3(580f, -305f, -462);
        paths[5] = new Vector3(-414, -263f, -462);
        paths[6] = new Vector3(137, -236f, -462);
        paths[7] = new Vector3(366, -266, -462);

        paths[8] = new Vector3(-140, -228, -462);
        paths[9] = new Vector3(660, -317, -462);


        HUIEventManager.Instance.AddUIEventListener(enUIEventID.Phonics_Back_Click, this.OnBackBtnClick);
        HUIEventManager.Instance.AddUIEventListener(enUIEventID.Phonics_Next_Letter, this.OnNextLetterClick);
        HUIEventManager.Instance.AddUIEventListener(enUIEventID.Phonics_Kcjs_Click, this.OpenKcjs);

        EventBus.Instance.AddEventHandler<int>(EventID.PHONICS_CLICK_LETTER, this.OnLetterClick);
        EventBus.Instance.AddEventHandler<bool>(EventID.PHONICS_GAME_END, this.OnGameEnd);
        EventBus.Instance.AddEventHandler<string>(EventID.GUIDAO_MOVE, this.GuiDaoMove);
        EventBus.Instance.AddEventHandler<bool>(EventID.SET_ZHUANPAN_ACTIVE, this.SetZhuanPanActive);
        EventBus.Instance.AddEventHandler<bool>(EventID.SET_LEDI2D_ACTIVE, this.SetLedi2DActive);

    }

    public override void UnInit()
    {
        base.UnInit();
        HUIEventManager.Instance.RemoveUIEventListener(enUIEventID.Phonics_Back_Click, this.OnBackBtnClick);
        HUIEventManager.Instance.RemoveUIEventListener(enUIEventID.Phonics_Next_Letter, this.OnNextLetterClick);

        EventBus.Instance.RemoveEventHandler<int>(EventID.PHONICS_CLICK_LETTER, this.OnLetterClick);
        EventBus.Instance.RemoveEventHandler<bool>(EventID.PHONICS_GAME_END, this.OnGameEnd);
        EventBus.Instance.RemoveEventHandler<string>(EventID.GUIDAO_MOVE, this.GuiDaoMove);
        EventBus.Instance.RemoveEventHandler<bool>(EventID.SET_ZHUANPAN_ACTIVE, this.SetZhuanPanActive);
        EventBus.Instance.RemoveEventHandler<bool>(EventID.SET_LEDI2D_ACTIVE, this.SetLedi2DActive);
    }

    public int CurLetter
    {
        get
        {
            return curLetter;
        }
    }

    #region ui
    public void OpenUI()
    {
        this.uiView = new StudyPhonicsUI();
        this.uiView.OpenUI();

        isLockInput = false;
        string zm = StudyPhonicsManager.Instance.GetLastLevel();
        if (!string.IsNullOrEmpty(zm))
        {
            if (zm != "Z")
            {
                char a = zm.ToCharArray()[0];
                string tempZM = ((char)((int)a + 1)).ToString();
                //Debug.Log("  tempZM ===  " + tempZM);
                //StudyPhonicsManager.Instance.LediMove(tempZM);
                //转转盘
                MoveTargetZp(tempZM);
            }
        }        
    }

    public void CloseUI()
    {
        this.uiView.CloseUI();
        this.uiView = null;
    }

    public void ShowEncourage()
    {

        //Debug.Log(curLetter + "  == ShowEncourage");
        //if (!isShowEncourage) return;

        this.uiView.SetEncourageView(true);
        this.uiView.PanelEncourage.GetComponent<PhonicsEncouragePanel>().SetLetter(CurLetter);
        switch (Random.Range(1, 4))
        {
            case 1:
                AudioManager.Instance.PlaySound(Itempathinfo.PhonicEggGamePath + "401020305");
                break;
            case 2:
                AudioManager.Instance.PlaySound(Itempathinfo.PhonicEggGamePath + "401020306");
                break;
            case 3:
                AudioManager.Instance.PlaySound(Itempathinfo.PhonicEggGamePath + "401020311");
                break;
        }


    }

    public void HideEncourage()
    {
        isLockInput = false;
        this.uiView.SetEncourageView(false);
    }

    private void OnBackBtnClick(HUIEvent evt)
    {
        if (isLockInput)
            return;
        isLockInput = true;

        AudioManager.Instance.StopAllSound();
        if (curGame != null)
        {
            curGame.SetActive();
            //if (this.model.GetGameType(curLetter) == emPhonicsGameType.Egg)             
        }

        isHideLd = false;
        SetLedi2DActive(true);
        //Debug.Log(" OnBackBtnClick =====  ");
        isShowEncourage = false;
        HideEncourage();
        this.uiView.PanelEncourage.GetComponent<PhonicsEncouragePanel>().SetLetterTrue();

        if (isGaming)
        {
            EventBus.Instance.BroadCastEvent<bool>(EventID.SET_ZHUANPAN_ACTIVE, true);

            EndGame();
        }
        else
        {
            Input.multiTouchEnabled = true;
            if (SDKManager.Instance.IsShowGZH())
            {
                WindowManager.Instance.OpenWindow(WinNames.EnglishMioPanel, EWindowFadeEnum.None, EWindowLayerEnum.PopupLayer);
                EnglishMioWindow.Instance.AddCloseEvent(() =>
                {
                    //回调事件
                    GameStateManager.Instance.GotoState(GameStateName.MAIN_STATE);
                });
            }
            else
            {
                GameStateManager.Instance.GotoState(GameStateName.MAIN_STATE);
            }

        }
    }

    private void OnAdsCallback(string adsName)
    {
        if (adsName == AdsNameConst.Ads_English.Name)
        {
            EventBus.Instance.RemoveEventHandler<string>(EventID.ADS_DONE_CALLBACK, OnAdsCallback);
            StudyEnglishProgressInfo info = LocalDataManager.Instance.Load<StudyEnglishProgressInfo>(ELocalDataType.StudyEnglishGame);
            info.zrpd_adsCount++;
            LocalDataManager.Instance.Save(ELocalDataType.StudyEnglishGame, info);
            isLockInput = false;
        }
    }

    private void OnNextLetterClick(HUIEvent evt)
    {
        if (isLockInput)
            return;
        isLockInput = true;

        AudioManager.Instance.StopAllSound();
        int tempcurLet = curLetter + 1;
        string l = ((char)tempcurLet).ToString();


#if UNITY_IOS

        if (l == "D" && !PayManager.Instance.IsBuyItem((int)MainItemEnum.StudyPhonics))
        {
            StudyEnglishProgressInfo info = LocalDataManager.Instance.Load<StudyEnglishProgressInfo>(ELocalDataType.StudyEnglishGame);
            if (info.zrpd_adsCount == 0)
            {
                EventBus.Instance.RemoveEventHandler<string>(EventID.ADS_DONE_CALLBACK, OnAdsCallback);
                EventBus.Instance.AddEventHandler<string>(EventID.ADS_DONE_CALLBACK, OnAdsCallback);
                
                TopNoticeManager.Instance.ShowOkTip(ADS_TIPS, () =>
                {
                    if (AdsManager.Instance.AdsReady(AdsNameConst.Ads_English))
                    {
                        AdsManager.Instance.ShowAds(AdsNameConst.Ads_English);
                    }
                    else
                    {
                        Debug.Log("广告还未准备好. name:" + AdsNameConst.Ads_English.Name);
                        isLockInput = false;
                    }
                }, () =>
                {
                    isLockInput = false;
                });

                return;
            }
        }

#endif


        if (l != "A" && l != "B" && l != "C" && l != "D" && !PayManager.Instance.IsBuyItem((int)MainItemEnum.StudyPhonics))
        {
            RemveEvent();
            EventBus.Instance.AddEventHandler(EventID.CANCEL_VERITY, this.OnCancelBuy);
            EventBus.Instance.AddEventHandler(EventID.CANCEL_PAY, this.OnCancelBuy);
            //调用购买
            PayManager.Instance.Pay((int)MainItemEnum.StudyPhonics, (id, suc) =>
            {
                //Debug.Log(id + "," + suc);
                if (id == (int)MainItemEnum.StudyPhonics && suc)
                {
                    if (curGame != null)
                    {
                        curGame.SetActive();
                    }
                    HideEncourage();
                    int tempcurLets = curLetter + 1;
                    string ls = ((char)tempcurLets).ToString();
                    Debug.LogError(" ls ==========  " + ls);
                    //移动转盘
                    if (ls == "F" || ls == "K" || ls == "P" || ls == "U")
                    {
                        isTurnLeDi = false;
                        this.uiView.GetZhuanPan().GetComponent<PhonicsLetterPanel>().MoveRight();
                    }
                    //去除需要购买图标
                    this.uiView.GetZhuanPan().GetComponent<PhonicsLetterPanel>().SetBuyIconState(false);
                    //改变乐迪位置
                    GuiDaoMove(ls);
                    //this.uiView.GetZhuanPan().transform.Find(l).GetComponent<PhonicsLetterItem>().OnPointerClick(null);
                    StartGame(tempcurLets);
                }
            }, true, AdsNameConst.Ads_English);
            return;
        }
        if (curGame != null)
        {
            curGame.SetActive();
        }
        HideEncourage();
        
        Debug.LogError(" l ==========  " + l);
        //移动转盘
        if (l == "F" || l == "K" || l == "P" || l == "U")
        {
            isTurnLeDi = false;
            this.uiView.GetZhuanPan().GetComponent<PhonicsLetterPanel>().MoveRight();
        }
        //改变乐迪位置
        GuiDaoMove(l);
        //this.uiView.GetZhuanPan().transform.Find(l).GetComponent<PhonicsLetterItem>().OnPointerClick(null);
        StartGame(tempcurLet);
    }
    
    private void RemveEvent()
    {
        EventBus.Instance.RemoveEventHandler(EventID.CANCEL_VERITY, this.OnCancelBuy);
        EventBus.Instance.RemoveEventHandler(EventID.CANCEL_PAY, this.OnCancelBuy);
    }

    private void OnCancelBuy()
    {
        RemveEvent();
        isLockInput = false;
    }

    private void OnLetterClick(int index)
    {

        string l = ((char)index).ToString();
        if (l == "A" || l == "F" || l == "K" || l == "P")
        {
        }
        StartGame(index);

    }

    private void OnGameEnd(bool done)
    {
        if (done && isShowEncourage)
        {
            AudioManager.Instance.PlaySound(Itempathinfo.PhonicEggGamePath + "603010706");
            this.ShowEncourage();

            //将通过记录 保存到持久化目录  存的是数字
            //if ((char)this.curLetter != 'A')
            if (!IsOverCurLevel(this.curLetter))
            {
                string datas = PlayerPrefs.GetString(phonicsrecord);
                if (!string.IsNullOrEmpty(datas))
                    datas = datas + this.curLetter + ",";
                else
                    datas = this.curLetter + ",";

                Debug.Log(datas + "  ==== PlayerPrefs data");
                PlayerPrefs.SetString(phonicsrecord, datas);

                //改变颜色
                this.uiView.GetZhuanPan().GetComponent<PhonicsLetterPanel>().SetItemColor(this.curLetter, true);
            }
            //改变轨道位置            
            //RefreshGuiDao(((char)this.curLetter).ToString());            
        }
    }
    public void MoveTargetZp(string l)
    {
        this.uiView.GetZhuanPan().GetComponent<PhonicsLetterPanel>().MoveTarget(l);
    }
    /// <summary>
    /// 改变轨道位置  
    /// </summary>
    /// <param name="l"></param>
    public void RefreshGuiDao(string l)
    {
        Debug.Log(l);
        //string l = ((char)this.curLetter).ToString();
        //往下移一格            this.uiView.GetGuiDao().fillAmount = 0.3f;
        if (l == "A" || l == "F" || l == "K" || l == "P" || l == "U")
            this.uiView.GetGuiDao().fillAmount = 0.45f;
        else if (l == "B" || l == "G" || l == "L" || l == "Q")
            this.uiView.GetGuiDao().fillAmount = 0.5f;
        else if (l == "C" || l == "H" || l == "M" || l == "R")
            this.uiView.GetGuiDao().fillAmount = 0.6f;
        else if (l == "D" || l == "I" || l == "N" || l == "S")
            this.uiView.GetGuiDao().fillAmount = 0.75f;
        else if (l == "E" || l == "J" || l == "O" || l == "T")
            this.uiView.GetGuiDao().fillAmount = 0.43f;
        else if (l == "V")
            this.uiView.GetGuiDao().fillAmount = 0.5f;
        else if (l == "W")
            this.uiView.GetGuiDao().fillAmount = 0.54f;
        else if (l == "X")
            this.uiView.GetGuiDao().fillAmount = 0.62f;
        else if (l == "Y")
            this.uiView.GetGuiDao().fillAmount = 0.75f;
        else if (l == "Z")
            this.uiView.GetGuiDao().fillAmount = 0.75f;
    }
    /// <summary>
    /// 查看数据记录是否通过这一关
    /// </summary>
    /// <param name="datas"></param>
    /// <param name="value"></param>
    /// <returns></returns>
    public bool IsOverCurLevel(int value)
    {
        string datas = PlayerPrefs.GetString(phonicsrecord);
        bool isOver = false;
        if (!string.IsNullOrEmpty(datas))
        {
            datas = datas.Trim(',');
            string[] strs = datas.Split(',');
            for (int i = 0; i < strs.Length; i++)
            {
                if (strs[i] == value.ToString())
                {
                    isOver = true;
                    break;
                }
            }
        }
        return isOver;
    }
    /// <summary>
    /// 获取最后一个通关字母
    /// </summary>
    /// <returns></returns>
    public string GetLastLevel()
    {
        string l = "";
        string datas = PlayerPrefs.GetString(phonicsrecord);
        if (!string.IsNullOrEmpty(datas))
        {
            datas = datas.Trim(',');
            string[] strs = datas.Split(',');
            l = strs[strs.Length - 1];
            l = ((char)(System.Convert.ToInt32(l))).ToString();
            //Debug.Log(l + "  ===== l");
        }
        return l;
    }
#endregion

    private void StartGame(int index)
    {
        //Debug.Log(index);
        this.curLetter = index;

        isShowEncourage = true;

        SDKManager.Instance.Event((int)UmengEvent.PhonicLetter + (this.curLetter - StartIndex));
        SDKManager.Instance.StartLevel((int)UmengLevel.PhonicLetter + (this.curLetter - StartIndex));

        isGaming = true;
        curGame = this.uiView.GetGame(this.model.GetGameType(index));
        curGame.Play();
    }

    private void EndGame()
    {
        SDKManager.Instance.FinishLevel((int)UmengLevel.PhonicLetter + (this.curLetter - StartIndex));
        isGaming = false;
        curGame.End(false);
        HideEncourage();
    }
     
    public void GuiDaoMove(string l)
    {
        LediMove(l);

        isHideLd = true;
        TimerManager.Instance.AddTimer(0.4f, () =>
        {
            if (isHideLd) this.SetLedi2DActive(false);
        });

    }
    public void LediMove(string l)
    {
        //Debug.Log(" lll ==== " + l);
        if (l == "A" || l == "F" || l == "K" || l == "P" || l == "U")
        {
            this.uiView.GetGuiDao().fillAmount = 0.3f;

            //在第一个位置的时候 判断乐迪的位置 有两种情况， 1 是点击字母  2 是翻页 
            if (this.uiView.GetLedi2d().transform.localPosition.x > paths[0].x && isTurnLeDi)
            {
                this.uiView.GetLedi2d().GetComponent<SpriteRenderer>().flipX = true;
                this.uiView.GetLedi2d().transform.DOLocalMove(new Vector3(paths[0].x + offsetX, paths[0].y + offsetY, paths[0].z), 0.4f);
            }
            else
            {
                this.uiView.GetLedi2d().GetComponent<SpriteRenderer>().flipX = false;
                this.uiView.GetLedi2d().transform.DOLocalMove(paths[0], 0.4f);
            }
        }
        else if (l == "B" || l == "G" || l == "L" || l == "Q")
        {
            this.uiView.GetGuiDao().fillAmount = 0.45f;
            if (this.uiView.GetLedi2d().transform.localPosition.x > paths[1].x)
            {
                this.uiView.GetLedi2d().transform.DOLocalMove(new Vector3(paths[1].x + offsetX, paths[1].y + offsetY, paths[1].z), 0.4f);
                this.uiView.GetLedi2d().GetComponent<SpriteRenderer>().flipX = true;

            }
            else
            {
                this.uiView.GetLedi2d().transform.DOLocalMove(paths[1], 0.4f);
                this.uiView.GetLedi2d().GetComponent<SpriteRenderer>().flipX = false;
            }
        }
        else if (l == "C" || l == "H" || l == "M" || l == "R")
        {
            this.uiView.GetGuiDao().fillAmount = 0.5f;

            if (this.uiView.GetLedi2d().transform.localPosition.x > paths[2].x)
            {
                this.uiView.GetLedi2d().transform.DOLocalMove(new Vector3(paths[2].x + offsetX, paths[2].y + offsetY, paths[2].z), 0.4f);
                this.uiView.GetLedi2d().GetComponent<SpriteRenderer>().flipX = true;

            }
            else
            {
                this.uiView.GetLedi2d().transform.DOLocalMove(paths[2], 0.4f);
                this.uiView.GetLedi2d().GetComponent<SpriteRenderer>().flipX = false;
            }
        }
        else if (l == "D" || l == "I" || l == "N" || l == "S")
        {
            this.uiView.GetGuiDao().fillAmount = 0.6f;

            if (this.uiView.GetLedi2d().transform.localPosition.x > paths[3].x)
            {
                this.uiView.GetLedi2d().transform.DOLocalMove(new Vector3(paths[3].x + offsetX, paths[3].y + offsetY, paths[3].z), 0.4f);
                this.uiView.GetLedi2d().GetComponent<SpriteRenderer>().flipX = true;

            }
            else
            {
                this.uiView.GetLedi2d().transform.DOLocalMove(paths[3], 0.4f);
                this.uiView.GetLedi2d().GetComponent<SpriteRenderer>().flipX = false;
            }
        }
        else if (l == "E" || l == "J" || l == "O" || l == "T")
        {
            this.uiView.GetGuiDao().fillAmount = 0.75f;

            if (this.uiView.GetLedi2d().transform.localPosition.x > paths[4].x)
            {
                this.uiView.GetLedi2d().transform.DOLocalMove(new Vector3(paths[4].x + offsetX, paths[4].y + offsetY, paths[4].z), 0.4f);
                this.uiView.GetLedi2d().GetComponent<SpriteRenderer>().flipX = true;

            }
            else
            {
                this.uiView.GetLedi2d().transform.DOLocalMove(paths[4], 0.4f);
                this.uiView.GetLedi2d().GetComponent<SpriteRenderer>().flipX = false;
            }
        }
        else if (l == "V")
        {
            this.uiView.GetGuiDao().fillAmount = 0.43f;

            if (this.uiView.GetLedi2d().transform.localPosition.x > paths[5].x)
            {
                this.uiView.GetLedi2d().transform.DOLocalMove(new Vector3(paths[5].x + offsetX, paths[5].y + offsetY, paths[5].z), 0.4f);
                this.uiView.GetLedi2d().GetComponent<SpriteRenderer>().flipX = true;

            }
            else
            {
                this.uiView.GetLedi2d().transform.DOLocalMove(paths[5], 0.4f);
                this.uiView.GetLedi2d().GetComponent<SpriteRenderer>().flipX = false;
            }
        }
        else if (l == "W")
        {
            this.uiView.GetGuiDao().fillAmount = 0.5f;

            if (this.uiView.GetLedi2d().transform.localPosition.x > paths[8].x)
            {
                this.uiView.GetLedi2d().transform.DOLocalMove(new Vector3(paths[8].x + offsetX, paths[8].y + offsetY, paths[8].z), 0.4f);
                this.uiView.GetLedi2d().GetComponent<SpriteRenderer>().flipX = true;

            }
            else
            {
                this.uiView.GetLedi2d().transform.DOLocalMove(paths[8], 0.4f);
                this.uiView.GetLedi2d().GetComponent<SpriteRenderer>().flipX = false;
            }
        }
        else if (l == "X")
        {
            this.uiView.GetGuiDao().fillAmount = 0.54f;
            if (this.uiView.GetLedi2d().transform.localPosition.x > paths[6].x)
            {
                this.uiView.GetLedi2d().transform.DOLocalMove(new Vector3(paths[6].x + offsetX, paths[6].y + offsetY, paths[6].z), 0.4f);
                this.uiView.GetLedi2d().GetComponent<SpriteRenderer>().flipX = true;

            }
            else
            {
                this.uiView.GetLedi2d().transform.DOLocalMove(paths[6], 0.4f);
                this.uiView.GetLedi2d().GetComponent<SpriteRenderer>().flipX = false;
            }
        }
        else if (l == "Y")
        {
            this.uiView.GetLedi2d().transform.DOLocalMove(paths[7], 0.4f);
            if (this.uiView.GetLedi2d().transform.localPosition.x > paths[7].x)
            {
                this.uiView.GetLedi2d().transform.DOLocalMove(new Vector3(paths[7].x + offsetX, paths[7].y + offsetY, paths[7].z), 0.4f);
                this.uiView.GetLedi2d().GetComponent<SpriteRenderer>().flipX = true;

            }
            else
            {
                this.uiView.GetLedi2d().transform.DOLocalMove(paths[7], 0.4f);
                this.uiView.GetLedi2d().GetComponent<SpriteRenderer>().flipX = false;
            }
            this.uiView.GetGuiDao().fillAmount = 0.62f;
        }
        else if (l == "Z")
        {
            this.uiView.GetGuiDao().fillAmount = 0.75f;

            if (this.uiView.GetLedi2d().transform.localPosition.x > paths[9].x)
            {
                this.uiView.GetLedi2d().transform.DOLocalMove(new Vector3(paths[9].x + offsetX, paths[9].y + offsetY, paths[9].z), 0.4f);
                this.uiView.GetLedi2d().GetComponent<SpriteRenderer>().flipX = true;

            }
            else
            {
                this.uiView.GetLedi2d().transform.DOLocalMove(paths[9], 0.4f);
                this.uiView.GetLedi2d().GetComponent<SpriteRenderer>().flipX = false;
            }
        }
    }

    private void SetZhuanPanActive(bool isActive)
    {

        this.uiView.GetZhuanPan().GetComponent<PhonicsLetterPanel>().enabled = isActive;
        this.uiView.GetZhuanPan().SetActive(isActive);
    }

    public void SetZhuanPanEnable(bool isEnable)
    {
        this.uiView.GetZhuanPan().GetComponent<PhonicsLetterPanel>().enabled = isEnable;
    }

    private void SetLedi2DActive(bool isActive)
    {
        this.uiView.GetLedi2d().SetActive(isActive);
    }

    private void OpenKcjs(HUIEvent evt)
    {

        WindowManager.Instance.OpenWindow(WinNames.EnglishZRPDKCJSPanel, EWindowFadeEnum.ScaleIn);
    }


}
